var HTMLParser = require('simple-html-parser');
var logger = require('./logger');
var util = require('./util');

function parseBrands(body) {
	var brands = new HTMLParser(body).getElementsByClassName('abrand', 'a');

	return brands.map(function(brand) {
		return {
			url: brand.attributes.href,
			name: util.trim(HTMLParser.decode(brand.innerHTML))
		};
	});
}


function parseCategories(body) {
	var hideBox = new HTMLParser(body).getElementById('hidebox');
	var categories = hideBox ? new HTMLParser(hideBox.innerHTML).getElementsByTagName('a') : [];
	
	return categories.map(function(category) {
		return {
			url: category.attributes.href,
			name: util.trim(HTMLParser.decode(category.innerHTML))
		};
	});;
}


function parseSubCategories(body) {
	
	var subCategories = new HTMLParser(body).getElementsByClassName('clsubclass')[0];
	if (!subCategories) {
		return [];
	}
	
	var categories = new HTMLParser(subCategories.innerHTML).getElementsByTagName('a');
	
	return categories.map(function(category) {
		return {
			url: category.attributes.href,
			name: util.trim(HTMLParser.decode(category.innerHTML))
		};
	});;
}


function parsePageCount(body) {
	var pagination = new HTMLParser(body).getElementsByClassName('manu')[0];
	
	return pagination && /of\s+(\d+)/.test(pagination.innerHTML) ? parseInt(RegExp.$1, 10) : 1;
}

function parseProductList(body) {
	var list = new HTMLParser(body).getElementsByClassName('plitem', 'div');
	var infos = [];
	list.forEach(function(item) {
		item = new HTMLParser(item.innerHTML);
		var box = item.getElementsByClassName('thickbox', 'a')[0];
		var img = item.getElementsByTagName('img')[0];
		var size = item.getElementsByClassName('size')[0];
		size = size && HTMLParser.decode(size.innerHTML).split(':')[1];
		
		if (!box || !img) {
			logger.error('not found product info...');
			return;
		}
		
		var isNew = item.getElementsByClassName('tagnew')[0];
		isNew = /<img/i.test(isNew && isNew.innerHTML);

		if (!/^(.*)\((.*)\)\n(.*)$/.test(box.attributes.title)) {
			logger.warn('Product information is not complete...');
		}
		
		infos.push({
				isNew: isNew,
				bigImg: box.attributes.href,
				smallImg: img.attributes.src,
				name: RegExp.$1,
				weight: RegExp.$2,
				price: RegExp.$3,
				size: size
		});
	});
	
	return infos;
}


module.exports = {
	parseBrands: parseBrands,
	parseCategories: parseCategories,
	parseSubCategories: parseSubCategories,
	parsePageCount: parsePageCount,
	parseProductList: parseProductList
};